#import "file_dialogue.h"
#include "sbrush_pantomime.h"

using namespace sbrush;

@implementation FileDialogue

+ (NSArray*) openModalWithTitle:(NSString*)title
					  extension:(NSString*)ext {
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	
	/* Configuer open panel */
	[openPanel setTitle:title];
	[openPanel setCanChooseFiles:YES];
	[openPanel setCanChooseDirectories:NO];
	[openPanel setResolvesAliases:YES];
	[openPanel setAllowsMultipleSelection:YES];
	[openPanel setAllowedFileTypes:[NSArray arrayWithObject:ext]];
	[openPanel setAllowsOtherFileTypes:YES];
	
	int result = [openPanel runModal];
	
	/* Get the result from whatever user action happened */
	if (result == NSFileHandlingPanelOKButton) {
		NSArray *filesToOpen = [openPanel URLs];
		NSMutableArray* fileItems = nil;
		fileItems = [NSMutableArray arrayWithCapacity:[filesToOpen count]];
		
		for (NSUInteger i = 0; i < [filesToOpen count]; i++) {
			NSURL *fileUrl = [filesToOpen objectAtIndex:i];
			FileItem* item = [[FileItem alloc] init];
			[item setPath:[fileUrl path]];
			[item setDisplay:[fileUrl lastPathComponent]];
			[fileItems insertObject:item atIndex:i];
		}
		return fileItems;
	}
	else {
		return [NSArray array];
	}
}

+ (void) saveModal:(FileItem*)fileItem
			 title:(NSString*)title
		 extension:(NSString*)ext {
	NSSavePanel *savePanel = [NSSavePanel savePanel];
	
	/* Configuer open panel */
	[savePanel setTitle:title];
	[savePanel setAllowedFileTypes:[NSArray arrayWithObject:ext]];
	[savePanel setAllowsOtherFileTypes:YES];
	
	int result = [savePanel runModal];
	
	/* Get the result from whatever user action happened */
	if (result == NSFileHandlingPanelOKButton) {
		NSURL *fileUrl = [savePanel URL];
		[fileItem setPath:[fileUrl path]];
		[fileItem setDisplay:[fileUrl lastPathComponent]];
		NSError* anError;
		if ([fileItem writeToFile:&anError] == YES) {
			[fileItem setSaved:YES];
		}
		else {
			NSAlert* alert = nil;
			if (anError != nil) {
				alert = [NSAlert alertWithError:anError];
			}
			else {
				alert = [NSAlert alertWithMessageText:@"Failed to save file"
											 defaultButton:nil
										   alternateButton:nil 
											   otherButton:nil
								 informativeTextWithFormat:@""];
			}
			[alert setAlertStyle:NSWarningAlertStyle];
			[alert runModal];
		}
	}
}

@end
